﻿
#region Copyright & License
// --------------------------
// Copyright 2008 Daniel Gray
// --------------------------
// This file is part of Kale.
//
// Kale is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Kale is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Kale.  If not, see <http://www.gnu.org/licenses/>.
#endregion
#region File details
// --------------------------------------------------------
// Filename          : Utility.cs
// Author            : Daniel Gray
// Created           : 07/05/2008
// --------------------------------------------------------
#endregion
            
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Kale.Core
{
   public static class Utility
   {
      /// <summary>
      /// Reads data into a complete array, throwing an EndOfStreamException
      /// if the stream runs out of data first, or if an IOException
      /// naturally occurs.
      /// </summary>
      /// <param name="stream">The stream to read data from</param>
      /// <param name="data">The array to read bytes into. The array
      /// will be completely filled from the stream, so an appropriate
      /// size must be given.</param>
      public static void ReadWholeArray(Stream stream, byte[] data)
      {
         int offset = 0;
         int remaining = data.Length;
         while (remaining > 0)
         {
            int read = stream.Read(data, offset, remaining);
            if (read <= 0)
               throw new EndOfStreamException
                   (String.Format("End of stream reached with {0} bytes left to read", remaining));
            remaining -= read;
            offset += read;
         }
      }

      public static void WriteWholeArray(Stream stream, byte[] data)
      {
         stream.Write(data, 0, data.Length);
      }
   }
}
